<template>
  <CustomScrollbar class="category-scroll">
    <div class="category">
      <div class="header" :style="{ background: categoryColor }">
        <div class="cover-gradient">
          <span class="icon">🎵</span>
        </div>
        <div class="info">
          <p class="type">分类</p>
          <h1 class="title">{{ categoryName }}</h1>
          <p class="stats">{{ songs.length }} 首歌曲</p>
        </div>
      </div>
      
      <div class="content">
        <div class="actions">
          <button class="play-all-btn" :disabled="songs.length === 0" @click="playAll">
            <span>▶</span> 播放全部
          </button>
          <button class="shuffle-btn" :disabled="songs.length === 0" @click="shufflePlay">
            <span>🔀</span> 随机播放
          </button>
        </div>
        
        <div class="songs-list">
          <div v-if="songs.length === 0" class="empty-state">
            <div class="empty-icon">🎵</div>
            <h3>该分类暂无音乐</h3>
            <p>等待更多音乐添加到这个分类</p>
            <button class="browse-btn" @click="$router.push('/')">浏览音乐</button>
          </div>
          
          <div v-else>
            <!-- 表格头部 -->
            <div class="table-header">
              <div class="header-cell header-index">#</div>
              <div class="header-cell header-title">标题</div>
              <div class="header-cell header-artist">艺人</div>
              <div class="header-cell header-album">专辑</div>
              <div class="header-cell header-duration">时长</div>
              <div class="header-cell header-actions"></div>
            </div>
            
            <!-- 歌曲列表 -->
            <div class="song-item" v-for="(song, index) in songs" :key="song.id"
                 @mouseenter="hoveredRow = index"
                 @mouseleave="hoveredRow = null">
              <div class="song-rank">
                <span v-if="hoveredRow !== index" class="track-number">{{ index + 1 }}</span>
                <button v-else class="play-btn" @click="playMusic(song)" title="播放">▶</button>
              </div>
              <div class="song-title-section">
                <img v-if="song.cover" :src="song.cover" :alt="song.name" class="song-thumbnail">
                <MusicIcon v-else :size="40" class="song-thumbnail" />
                <div class="song-details">
                  <div class="song-name">{{ song.name }}</div>
                  <div class="song-artist-mobile">{{ song.singer }}</div>
                </div>
              </div>
              <div class="song-artist">{{ song.singer }}</div>
              <div class="song-album">{{ song.album || '未知专辑' }}</div>
              <div class="song-duration">{{ formatDuration(song.duration) }}</div>
              <div class="song-actions">
                <button class="action-btn" @click="toggleFavorite(song)"
                        :class="{ 'favorited': isFavorite(song.id) }" title="收藏/取消收藏">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                    <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                  </svg>
                </button>
                <button class="action-btn" @click="playMusic(song)">▶</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { musicAPI, playlistAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'CategoryView',
  data() {
    return {
      categoryName: '',
      categoryDescription: '',
      categoryColor: '',
      songs: [],
      hoveredRow: null
    }
  },
  
  computed: {
    favorites() {
      return this.$store.state.player.favorites || []
    }
  },
  
  async created() {
    const categoryId = parseInt(this.$route.params.id)
    await this.loadCategoryData(categoryId)
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
  },
  
  watch: {
    async '$route'() {
      const categoryId = parseInt(this.$route.params.id)
      await this.loadCategoryData(categoryId)
    }
  },
  
  methods: {
    async loadCategoryData(categoryId) {
      if (!categoryId) {
        console.warn('分类ID无效:', categoryId)
        return
      }
      
      console.log('加载分类数据:', categoryId)
      
      try {
        // 从API获取分类信息
        const { categoryAPI } = await import('@/utils/api')
        let categoryInfo = null
        
        try {
          const categoryResponse = await categoryAPI.getAllCategories()
          if (categoryResponse.success && categoryResponse.categories) {
            categoryInfo = categoryResponse.categories.find(cat => cat.categoryId === categoryId)
          }
        } catch (apiError) {
          console.error('从API获取分类信息失败:', apiError)
          throw new Error('无法获取分类信息')
        }
        
        // 如果找不到分类信息，抛出错误
        if (!categoryInfo) {
          throw new Error(`分类 ${categoryId} 不存在`)
        }
        
        // 格式化API返回的数据
        this.categoryName = categoryInfo.name || '未知分类'
        this.categoryDescription = categoryInfo.description || ''
        this.categoryColor = categoryInfo.gradient || categoryInfo.color || 'linear-gradient(135deg, #666, #888)'
        
        // 从音乐API加载该分类的歌曲
        const { musicAPI } = await import('@/utils/api')
        
        try {
          // 尝试直接获取分类音乐
          const musicResponse = await musicAPI.getMusicByCategory(categoryId, 0, 100)
          if (musicResponse.success && musicResponse.music) {
            this.songs = musicResponse.music.map(music => ({
              id: music.musicId,
              name: music.name,
              singer: music.singer,
              artist: music.singer,
              album: music.album || '未知专辑',
              duration: music.duration,
              cover: music.coverPath ? this.buildCoverUrl(music.coverPath) : null,
              filePath: music.filePath,
              isExternal: music.filePath && (music.filePath.startsWith('http') || music.filePath.includes('url:'))
            }))
            console.log('加载分类音乐:', this.songs.length, '首')
            return
          }
        } catch (categoryMusicError) {
          console.warn('获取分类音乐失败，尝试获取所有音乐:', categoryMusicError)
        }
        
        // 如果分类音乐API失败，尝试获取所有音乐并过滤
        try {
          const allMusicResponse = await musicAPI.getAllMusic(0, 100)
          if (allMusicResponse.music && allMusicResponse.music.length > 0) {
            // 过滤出属于当前分类的歌曲
            this.songs = allMusicResponse.music
              .filter(music => {
                // 只显示真正属于当前分类的音乐
                if (music.category && music.category.categoryId) {
                  return music.category.categoryId === categoryId
                }
                // 如果没有分类信息，不显示
                return false
              })
              .map(music => ({
                id: music.musicId,
                name: music.name,
                singer: music.singer,
                artist: music.singer,
                album: music.album || '未知专辑',
                duration: music.duration,
                cover: music.coverPath ? this.buildCoverUrl(music.coverPath) : null,
                filePath: music.filePath,
                isExternal: music.filePath && (music.filePath.startsWith('http') || music.filePath.includes('url:'))
              }))
            
            console.log('加载分类音乐:', this.songs.length, '首')
          } else {
            this.songs = []
          }
        } catch (allMusicError) {
          console.error('加载所有音乐失败:', allMusicError)
          this.songs = []
        }
        
      } catch (error) {
        console.error('加载分类数据失败:', error)
        // 显示错误状态
        this.categoryName = '加载失败'
        this.categoryDescription = error.message || '分类信息加载失败'
        this.categoryColor = 'linear-gradient(135deg, #666, #888)'
        this.songs = []
        
        // 显示错误提示
        this.$toast?.error(error.message || '分类信息加载失败')
      }
    },
    
    buildCoverUrl(coverPath) {
      if (!coverPath) return null
      if (coverPath.startsWith('http')) return coverPath
      return `${process.env.VUE_APP_API_BASE_URL || 'http://localhost:2025'}${coverPath}`
    },
    
    async playMusic(song) {
      try {
        console.log('播放音乐:', song.name)
        
        const musicData = {
          musicId: song.id,
          name: song.name,
          title: song.name,
          singer: song.singer,
          artist: song.singer,
          coverPath: song.cover,
          filePath: song.filePath,
          duration: song.duration
        }
        
        await this.$store.dispatch('player/playMusic', musicData)
        // 设置当前分类的歌曲为播放列表
        this.$store.dispatch('player/setPlaylist', this.songs.map(s => ({
          musicId: s.id,
          name: s.name,
          title: s.name,
          singer: s.singer,
          artist: s.singer,
          coverPath: s.cover,
          filePath: s.filePath,
          duration: s.duration
        })))
      } catch (error) {
        console.error('播放音乐失败:', error)
        this.$toast?.error('播放失败，请稍后重试')
      }
    },
    
    async playAll() {
      if (this.songs.length === 0) return
      
      try {
        // 播放第一首歌曲
        await this.playMusic(this.songs[0])
      } catch (error) {
        console.error('播放全部失败:', error)
        this.$toast?.error('播放失败，请稍后重试')
      }
    },
    
    async shufflePlay() {
      if (this.songs.length === 0) return
      
      try {
        // 开启随机播放模式
        this.$store.dispatch('player/toggleShuffle')
        // 播放第一首歌曲
        await this.playMusic(this.songs[0])
      } catch (error) {
        console.error('随机播放失败:', error)
        this.$toast?.error('播放失败，请稍后重试')
      }
    },
    
    async toggleFavorite(song) {
      try {
        const musicData = {
          musicId: song.id,
          name: song.name,
          title: song.name,
          singer: song.singer,
          artist: song.singer,
          coverPath: song.cover,
          filePath: song.filePath,
          duration: song.duration
        }
        
        await this.$store.dispatch('player/toggleFavorite', musicData)
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$toast?.error('收藏操作失败，请稍后重试')
      }
    },
    
    isFavorite(musicId) {
      return this.$store.getters['player/favorites'].includes(musicId)
    },
    
    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    }
  }
}
</script>

<style scoped>
.category-scroll {
  height: 100%;
}

.category {
  padding-bottom: 24px;
}

.header {
  padding: 32px;
  display: flex;
  align-items: flex-end;
  gap: 24px;
}

.cover-gradient {
  width: 160px;
  height: 160px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3rem;
  color: white;
  box-shadow: 0 4px 60px rgba(0, 0, 0, 0.3);
}

.info {
  flex: 1;
}

.type {
  font-size: 12px;
  font-weight: bold;
  color: white;
  margin: 0 0 8px 0;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.title {
  font-size: 3rem;
  font-weight: bold;
  color: white;
  margin: 0 0 16px 0;
}

.stats {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
}

.content {
  padding: 32px;
  background: linear-gradient(180deg, rgba(69, 10, 245, 0.2) 0%, #121212 20%);
}

.actions {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.play-all-btn {
  background: #1DB954;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 50px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s;
}

.play-all-btn:hover {
  background: #1ed760;
  transform: scale(1.04);
}

.play-all-btn:disabled {
  background: #535353;
  cursor: not-allowed;
  transform: none;
}

.shuffle-btn {
  background: none;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 12px 24px;
  border-radius: 50px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s;
}

.shuffle-btn:hover {
  border-color: white;
  background: rgba(255, 255, 255, 0.1);
}

.shuffle-btn:disabled {
  border-color: rgba(255, 255, 255, 0.1);
  color: #535353;
  cursor: not-allowed;
}

.songs-list {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;
}

.empty-state {
  text-align: center;
  padding: 64px 32px;
  color: #b3b3b3;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  color: white;
  font-size: 2rem;
  margin-bottom: 16px;
}

.browse-btn {
  background: #1DB954;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 24px;
  transition: background 0.2s;
}

.browse-btn:hover {
  background: #1ed760;
}

.table-header {
  display: grid;
  grid-template-columns: 60px 1fr 200px 200px 80px 120px;
  gap: 16px;
  padding: 12px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 8px;
}

.header-cell {
  color: #b3b3b3;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
}

.header-duration {
  justify-content: center;
}

.song-item {
  display: grid;
  grid-template-columns: 60px 1fr 200px 200px 80px 120px;
  gap: 16px;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  transition: background 0.2s;
}

.song-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.song-item:last-child {
  border-bottom: none;
}

.song-rank {
  text-align: center;
  color: #b3b3b3;
  font-weight: bold;
}

.track-number {
  color: #b3b3b3;
  font-weight: 500;
}

.play-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.play-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.1);
}

.song-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.song-thumbnail {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  flex-shrink: 0;
}

.song-details {
  min-width: 0;
  flex: 1;
}

.song-artist-mobile {
  display: none;
}

.song-name {
  font-size: 16px;
  font-weight: 500;
  color: white;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.song-artist {
  font-size: 14px;
  color: #b3b3b3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-album {
  color: #b3b3b3;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-duration {
  color: #b3b3b3;
  text-align: center;
  font-variant-numeric: tabular-nums;
}

.song-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.song-item:hover .song-actions {
  opacity: 1;
}

.action-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
}

.action-btn.favorited {
  color: #1DB954 !important;
}

.action-btn.favorited svg {
  color: #1DB954 !important;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .table-header,
  .song-item {
    grid-template-columns: 50px 1fr 150px 150px 70px 100px;
    gap: 12px;
  }
  
  .header {
    padding: 24px;
  }
  
  .content {
    padding: 24px;
  }
  
  .title {
    font-size: 2.5rem;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    text-align: center;
    padding: 32px 16px;
  }
  
  .cover-gradient {
    width: 192px;
    height: 192px;
  }
  
  .title {
    font-size: 3rem;
  }
  
  .content {
    padding: 16px;
  }
  
  .table-header,
  .song-item {
    grid-template-columns: 40px 1fr 80px 80px;
    gap: 8px;
    padding: 8px 12px;
  }
  
  .song-artist,
  .song-album {
    display: none;
  }
  
  .song-artist-mobile {
    display: block;
    font-size: 14px;
    color: #b3b3b3;
  }
}
</style> 